package com.epam.cdp.selenium2.core.runner;

import org.apache.log4j.MDC;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import com.epam.cdp.selenium2.core.results.logger.Logger;
import com.epam.cdp.selenium2.core.results.logger.LoggerLevel;

/**
 * @author yyudzitski
 */
public class TestListener extends TestListenerAdapter implements IInvokedMethodListener
{
  public final static int CONFIGURATION_METHOD = 0;

  public final static int TEST_METHOD = 1;

  void setMDC( ITestContext testContext )
  {
    MDC.put( "testContext", testContext );
  }

  void setMDC( ITestResult result )
  {
    MDC.put( "testResult", result );
  }

  private String getCaseName( ITestResult result )
  {
    return result.getTestClass().getRealClass().getSimpleName() + "." + result.getMethod().getMethodName();
  }

  public void beforeInvocation( IInvokedMethod method, ITestResult testResult )
  {
    if( !method.isTestMethod() )
    {
      Logger.getLogger().log( LoggerLevel.CONFIGURATION_STARTED, getCaseName( testResult ) );
    }
  }

  public void afterInvocation( IInvokedMethod method, ITestResult testResult )
  {
  }

  @Override
  public void onStart( ITestContext testContext )
  {
    Logger.getLogger().log( LoggerLevel.TEST_STARTED, testContext.getName() );
  }

  @Override
  public void onFinish( ITestContext testContext )
  {
    Logger.getLogger().log( LoggerLevel.TEST_FINISHED, testContext.getName() );
  }

  @Override
  public void onConfigurationFailure( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.CONFIGURATION_FAILED, getCaseName( testResult ) );
  }

  @Override
  public void onConfigurationSuccess( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.CONFIGURATION_SUCCESS, getCaseName( testResult ) );
  }

  @Override
  public void onConfigurationSkip( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.CONFIGURATION_SKIPPED, getCaseName( testResult ) );
  }

  @Override
  public void onTestStart( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.METHOD_STARTED, getCaseName( testResult ) );
  }

  @Override
  public void onTestSuccess( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.METHOD_SUCCESS, getCaseName( testResult ) );
  }

  @Override
  public void onTestFailure( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.METHOD_FAILED, getCaseName( testResult ) );
    testResult.getThrowable().printStackTrace();
  }

  @Override
  public void onTestSkipped( ITestResult testResult )
  {
    Logger.getLogger().log( LoggerLevel.METHOD_SKIPPED, getCaseName( testResult ) );
  }
}